/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
Ext.define('Nothing.controller.Users', {
    extend: 'Ext.app.Controller',

    stores: ['Users', 'Roles'],
    views: ['user.UserManage'],

    refs: [
        {
            ref: 'search',
            selector: 'usersearch'
        }
    ],

    init: function () {
        window.uctrl = this;
        var me = this;
        this.control({
            'userlist': {
                itemdblclick: this.editUser
            },

            'usersearch': {
                search: Ext.Function.bind(this.searchFilter, this)//this.searchFilter
            },

            'userlist button[action=search-adv]': {
                click: function () {
                    var search = me.getSearch();
                    search.setVisible(search.hidden);
                }
            },

            'useredit': {
                update: this.doUpdate
            }
        });
    },

    editUser: function (grid, record) {
        //Ext.widget('useredit').down('form').loadRecord(record);
    },

    doUpdate: function (win, form) {
        var me = this;
        var record = form.getRecord();

        // this.store.
        record.set(form.getValues());
        me.getUsersStore().sync({
            // 覆盖失败的处理
            failure: function (batch, options) {
                me.getUsersStore().rejectChanges();
            }
        });
        win.close();

        // TODO
    },

    searchFilter: function (search, button, filters) {
        button.setDisabled(true);
        var store = this.getUsersStore();

        if (!Ext.isArray(filters)) {
            filters = undefined === filters ? [] : [filters];
        }

        // 直接调用store方法eg: store.clearFilter() 会触发请求
        // TODO 默认过滤条件处理
        store.filters.clear();
        store.filters.addAll(filters);
        // 这里使用替换, 避免替换掉默认过滤, 不行, 这样条件会叠加...
        // store.replace(filters[0])

        store.loadPage(1, {
            callback: function () {
                button.setDisabled(false);
            }
        });
    }
});
